package com.h3c.ptability.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.constant.StatusCodeEnum;
import com.eos.common.custom.BusinessException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.h3c.ptability.entity.PtAllWorker;
import com.h3c.ptability.entity.PtApp;
import com.h3c.ptability.entity.PtTodoTask;
import com.h3c.ptability.mapper.PtAppMapper;
import com.h3c.ptability.mapper.PtTodoTaskMapper;
import com.h3c.ptability.service.CommService;
import com.h3c.ptability.service.IPtTodoTaskService;
import com.h3c.ptability.dto.PtTodoTaskDTO;
import com.h3c.ptability.utils.AppBusinessException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: PtTodoTaskServiceImpl
 *
 * @Author: l22886
 * @Date: 2022-03-14
 * Description: pt_todo_task serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
public class PtTodoTaskServiceImpl extends ServiceImpl<PtTodoTaskMapper, PtTodoTask> implements IPtTodoTaskService {

    @Resource
    private PtTodoTaskMapper ptTodoTaskMapper;

    @Autowired
    private CommService commService;

    @Resource
    private PtAppMapper ptAppMapper;

    //配置项添加代办账号密码
    @Value("${sd.todotask.sysid}")
    private String todoTaskSysId;

    @Value("${sd.todotask.syspwd}")
    private String todoTaskSysPwd;

    @Value("${ssc.todo.url}")
    private String toDoUrl;

    @Value("${todotask.url}")
    private String toDoTaskUrl;


    @Value("${hrMrs.todotask.pwd}")
    private String hrMrsPwd;

    @Value("${hrsign.todotask.pwd}")
    private String hrSignPwd;

    @Value("${hrRecruitment.todotask.pwd}")
    private String hrRecruitmentPwd;

    @Value("${hrcpsse.todotask.pwd}")
    private String hrcpssePwd;

    @Value("${hrcsms.todotask.pwd}")
    private String hrcsmsPwd;
    /**
     * @title: selectFuzzyByDto
     * @description: 模糊查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<PtTodoTaskDTO> selectFuzzyByDto(PtTodoTaskDTO dto) {
        try {
            PtApp ptApp = ptAppMapper.selectById(dto.getAppid());
            if (StringUtils.isEmpty(ptApp.getSystemid())) {
                return new ArrayList<>();
            }
            dto.setSystemid(ptApp.getSystemid());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startTime = dto.getStartTime();
            String endTime = dto.getEndTime();
            Date startDate = null;
            Date endDate = null;
            if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
                startDate = simpleDateFormat.parse(startTime);
                endDate = simpleDateFormat.parse(endTime);
            }
            PtTodoTask todoTask = JSONObject.parseObject(JSONObject.toJSONString(dto), PtTodoTask.class);
            //前端传参，当前处理人是工号，待办字段为域账号
            if (!StringUtils.isEmpty(dto.getAuthorid())) {
                PtAllWorker worker = commService.getAllWorkerByWorkerId(dto.getAuthorid());
                if (!ObjectUtils.isEmpty(worker)) {
                    dto.setAuthorid(worker.getDomainAccount());
                }
            }
            List<PtTodoTask> list = ptTodoTaskMapper.queryListByFuzzy(todoTask, startDate, endDate);
            return JSONArray.parseArray(JSONArray.toJSONString(list), PtTodoTaskDTO.class);
        } catch (Exception e) {
            log.error("查询失败:", e);
            return new ArrayList<>();
        }
    }

    /**
     * @title: selectByDto
     * @description: 精确查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<PtTodoTaskDTO> selectByDto(PtTodoTaskDTO dto) {
        //List<PtTodoTask> list = ptTodoTaskMapper.selectByExample(initExample(dto));
        List<PtTodoTask> list = ptTodoTaskMapper.queryList(JSONObject.parseObject(JSONObject.toJSONString(dto), PtTodoTask.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), PtTodoTaskDTO.class);
    }

    /**
     * @title: insertDto
     * @description: 插入操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer insertDto(PtTodoTaskDTO dto) {
        //if (null == dto.getId() || "".equals(dto.getId())) {
        //    String pkId = idWorker.nextId() + "";
        //    dto.setId(pkId);
        //}
        return ptTodoTaskMapper.insertPtTodoTask(JSONObject.parseObject(JSON.toJSONString(dto), PtTodoTask.class));
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer updateDto(PtTodoTaskDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        return ptTodoTaskMapper.updatePtTodoTask(JSONObject.parseObject(JSON.toJSONString(dto), PtTodoTask.class));
        //return ptTodoTaskMapper.updateByPrimaryKey(JSONObject.parseObject(JSON.toJSONString(dto), PtTodoTask.class));
        //} else {
        //    return 0;
        //}
    }

    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer deleteDto(PtTodoTaskDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        return ptTodoTaskMapper.deletePtTodoTask(JSONObject.parseObject(JSON.toJSONString(dto), PtTodoTask.class));
        //return ptTodoTaskMapper.deleteByPrimaryKey(dto.getId());
        //} else {
        //    return 0;
        //}
    }

    @Override
    @Transactional
    public Boolean initOrUpdateTodoTask(PtTodoTaskDTO ptTodoTaskDTO) {
        String systemid = ptTodoTaskDTO.getSystemid();
        String docunid = ptTodoTaskDTO.getDocunid();
        String processid = ptTodoTaskDTO.getProcessid();

        QueryWrapper<PtTodoTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(PtTodoTask::getSystemid, systemid)
                .eq(PtTodoTask::getDocunid, docunid)
                .eq(PtTodoTask::getProcessid, processid);
        List<PtTodoTask> todoTasks = ptTodoTaskMapper.selectList(queryWrapper);
        PtTodoTask ptTodoTask = JSONObject.parseObject(JSON.toJSONString(ptTodoTaskDTO), PtTodoTask.class);
        if (todoTasks.isEmpty()) {
            ptTodoTaskMapper.insert(ptTodoTask);
        } else {
            //如果存在待办 不更新申请人跟申请时间 审批人在原基础上增加
            PtTodoTask dbTask = todoTasks.get(0);
            if (!dbTask.getEnduserid().equals("")) {
                ptTodoTask.setEnduserid(dbTask.getEnduserid() + "," + ptTodoTask.getEnduserid());
            }
            ptTodoTaskMapper.update(ptTodoTask, queryWrapper);
        }
        sendTodoTask(ptTodoTask);
        return Boolean.TRUE;
    }

    /**
     * 调用中台接口发布待办
     *
     * @param dto
     */
    private void sendTodoTask(PtTodoTask dto) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(dto);
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            httpHeaders.set("sysid", todoTaskSysId);
            httpHeaders.set("syspwd", todoTaskSysPwd);
            httpHeaders.set("userId", jsonObject.getString("adduserid"));
            HttpEntity<JSONObject> requestEntity = new HttpEntity<>(jsonObject, httpHeaders);
            ResponseEntity<String> responseJSONObject = restTemplate.exchange(toDoUrl, HttpMethod.POST, requestEntity, String.class);
            Object success = JSONObject.parseObject(responseJSONObject.getBody()).get("success");
            log.info(success + "==============================================================");
            log.info(responseJSONObject.toString());
            if (success.equals(false)) {
                throw new BusinessException(StatusCodeEnum.UNKNOW_ERROR.getCode(), "发送待办至队列失败");
            }
        } catch (Exception e) {
            log.error("发送待办至队列失败", e);
            throw new BusinessException(StatusCodeEnum.UNKNOW_ERROR.getCode(), "发送待办至队列失败");
        }
    }

    /**
     * 待办查询
     */
    @Override
    public PtTodoTask getTodoTaskTwo(PtTodoTask todoTask) {
        QueryWrapper<PtTodoTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PtTodoTask::getSystemid, todoTask.getSystemid())
                .eq(PtTodoTask::getNodeid, todoTask.getNodeid())
                .eq(PtTodoTask::getDocunid, todoTask.getDocunid());
        return getOne(queryWrapper);
    }


    /**
     * 待办中心待办创建或更新(支持多系统，需要传自己的账号密码)
     */
    @Override
    public void sendTodoTaskNew(PtTodoTask dto) {
        //        String loginUserDomainAccount = getLoginDomainAccount();
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(dto);
        try {

            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            httpHeaders.set("sysid", dto.getSystemid());
            //不同系统使用公共能力的待办，请在此处设置自己的密码
            if ("HRMRS".equals(dto.getSystemid())) {
                String systemPwd = hrMrsPwd;
                httpHeaders.set("syspwd", systemPwd);
            } else if ("HR_SIGN".equals(dto.getSystemid())) {
                String systemPwd = hrSignPwd;
                httpHeaders.set("syspwd", systemPwd);
            } else if ("HR_RECRUITMENT".equals(dto.getSystemid())) {
                String systemPwd = hrRecruitmentPwd;
                httpHeaders.set("syspwd", systemPwd);
            } else if ("HRCP-SSE".equals(dto.getSystemid())) {
                String systemPwd = hrcpssePwd;
                httpHeaders.set("syspwd", systemPwd);
            } else if ("HR_CSMS".equals(dto.getSystemid())){
                String systemPwd = hrcsmsPwd;
                httpHeaders.set("syspwd", systemPwd);
            } else {
                throw new AppBusinessException("请于公共能力配置待办密码！");
            }
//            httpHeaders.set("userId",getLoginDomainAccount());
            httpHeaders.set("userId", jsonObject.getString("adduserid"));
            HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(jsonObject, httpHeaders);
            ResponseEntity<String> responseJSONObject = restTemplate.exchange(toDoTaskUrl, HttpMethod.POST, requestEntity, String.class);
            Object success = JSONObject.parseObject(responseJSONObject.getBody()).get("success");
            log.info(success + "==============================================================");
            log.info(responseJSONObject.toString());
            if (success.equals(false)) {
                throw new AppBusinessException("发送待办至队列失败");
            }
        } catch (Exception e) {
            System.out.println("发送待办至队列失败");
            e.printStackTrace();
            throw new AppBusinessException("发送待办至队列失败");
        }
    }

    /**
     * 待办中心待办创建或更新(支持多系统，需要在参数中传自己的账号密码)
     */
    @Override
    public void sendTodoTaskNewWithPw(PtTodoTaskDTO dto) {
        //        String loginUserDomainAccount = getLoginDomainAccount();
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(dto);
        try {

            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            httpHeaders.set("sysid", dto.getSystemid());
            httpHeaders.set("syspwd", dto.getSysPwd());

            httpHeaders.set("userId", dto.getAdduserid());
            HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(jsonObject, httpHeaders);
            ResponseEntity<String> responseJSONObject = restTemplate.exchange(toDoTaskUrl, HttpMethod.POST, requestEntity, String.class);
            Object success = JSONObject.parseObject(responseJSONObject.getBody()).get("success");
            log.info(success + "==============================================================");
            log.info(responseJSONObject.toString());
            if (success.equals(false)) {
                throw new AppBusinessException("发送待办至队列失败");
            }
        } catch (Exception e) {
            System.out.println("发送待办至队列失败");
            e.printStackTrace();
            throw new AppBusinessException("发送待办至队列失败");
        }
    }

    /**
     * 本地待办创建或更新
     */
    @Override
    public void addOrUpdateTodoTask(PtTodoTask todoTask) {
        if (todoTask.getRedirecturl() == null) {
            todoTask.setRedirecturl("");
        }
        try {
            QueryWrapper<PtTodoTask> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(PtTodoTask::getSystemid, todoTask.getSystemid())
                    .eq(PtTodoTask::getProcessid, todoTask.getProcessid())
                    .eq(PtTodoTask::getDocunid, todoTask.getDocunid());
            boolean i = update(todoTask, queryWrapper);
            if (!i) {
                save(todoTask);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
